﻿
Friend Class FT8BinaryDictionary
    Public Shared Instance As Integer = 0
    Dim PreviousNode As FT8BinaryDictionary
    Dim NextNode As New Dictionary(Of Char, FT8BinaryDictionary)
    Dim EndMark As Boolean = False

    Public Sub New()
        PreviousNode = Nothing
        Instance += 1
    End Sub

    Private Sub New(ByVal Previous As FT8BinaryDictionary)
        PreviousNode = Previous
        Instance += 1
    End Sub

    Public Sub Add(ByVal Word As String)

        Dim CurrentChar As Char = Word.First

        If NextNode.Keys.Contains(CurrentChar) Then
            Dim Node As FT8BinaryDictionary = NextNode(CurrentChar)
            Dim NewWord As String = Word.Substring(1)
            If NewWord = "" Then
                EndMark = True
            Else
                Node.Add(NewWord)
            End If
        Else
            Dim Node As New FT8BinaryDictionary(Me)
            Me.NextNode.Add(CurrentChar, Node)
            Dim NewWord As String = Word.Substring(1)
            If NewWord <> "" Then
                Node.Add(NewWord)
                Exit Sub
            Else
                EndMark = True
            End If
        End If
    End Sub

    Public Function Contains(ByVal Word As String) As Boolean
        If Word.Length = 1 Then
            If Me.EndMark Then
                If Me.NextNode.Keys.Contains(CChar(Word)) Then
                    Return True
                End If
                Return False
            Else
                Return False
            End If
        End If
        Dim CurrentChar As Char = Word.First
        If NextNode.Keys.Contains(CurrentChar) Then
            Dim Node As FT8BinaryDictionary = NextNode(CurrentChar)
            Dim NewWord As String = Word.Substring(1)
            Return Node.Contains(NewWord)
        Else
            Return False
        End If

    End Function

    'TODO === Revisit to remove garbage===========================
    Public Function Remove(ByVal Word As String) As Boolean
        If Word.Length = 1 Then
            If Me.EndMark Then
                If Me.NextNode.Keys.Contains(CChar(Word)) Then
                    Me.EndMark = False
                    Return True
                End If
                Return False
            Else
                Return False
            End If
        End If
        Dim CurrentChar As Char = Word.First
        If NextNode.Keys.Contains(CurrentChar) Then
            Dim Node As FT8BinaryDictionary = NextNode(CurrentChar)
            Dim NewWord As String = Word.Substring(1)
            Return Node.Remove(NewWord)
        Else
            Return False
        End If
    End Function

End Class